var d = {};
(function($) {
	$.fn.hint = function(txt, cb) {
		return $(this).each(
				function() {
					$(this).data("hint", txt).focus(function() {
						if ($.trim($(this).val()) === txt) {
							$(this).val("").removeClass("hintText");
							if (cb) {
								cb(false);
							}
						}
					}).blur(
							function() {
								if ($.trim($(this).val()) === ""
										|| $.trim($(this).val()) === txt) {
									$(this).val(txt).addClass("hintText");
									if (cb) {
										cb(true);
									}
								}
							}).trigger("blur");
				});
	};
	$.fn.isHint = function() {
		return $.trim($(this).val()) === $(this).data("hint");
	};
	$.fn.nhVal = function(val) {
		if (arguments.length > 0) {
			$(this).val(val || $(this).data("hint"));
			$(this).toggleClass("hintText", $(this).isHint());
		} else {
			return $(this).isHint() ? "" : $.trim($(this).val());
		}
	};
	$.fn.subst = function(content) {
		$(this).empty().append(content);
	};
	$.fn.addPremiumNag = function() {
		var premiumNag = $('<div id="premiumNag" class="clearfix"/>').append(
				'<img src="/graphics/premium/pdLogoLarge.png"').append(
				$('<div/>').append(
						$('<h5 class="blue"/>').text(
								d.utils.l10n.staticpaidtitle)).append(
						$('<p/>').text(
								d.utils.l10n.featureRequiresPaidSubscription))
						.append(
								$('<a href="/premium/plans.html"/>').text(
										d.utils.l10n.moreOnThat + "...")));
		$(this).qtip({
			content : premiumNag,
			show : 'mouseover',
			hide : {
				when : "mouseout",
				fixed : true
			},
			position : {
				corner : {
					target : 'topMiddle',
					tooltip : 'bottomMiddle'
				}
			},
			style : {
				padding : 1,
				background : '#fff',
				color : 'black',
				textAlign : 'center',
				border : {
					width : 1,
					radius : 1,
					color : '#d6d6d6'
				},
				tip : "bottomMiddle",
				name : 'light'
			}
		});
	};
	$.fn.busy = function() {
		return $(this).each(function() {
			$(this).attr("disabled", true).after('<div class="busy"/>');
		});
	};
	$.fn.unbusy = function() {
		return $(this).each(function() {
			$(this).removeAttr("disabled").siblings("div.busy").remove();
		});
	};
	$.fn.animateIn = function(cb) {
		return $(this).each(function() {
			$(this).slideDown("fast", cb);
		});
	};
	$.fn.animateOut = function(cb) {
		return $(this).each(function() {
			$(this).slideUp("fast", cb);
		});
	};
	$.fn.animateToggle = function(cb) {
		return $(this).each(function() {
			if ($(this).css("display") === "none") {
				$(this).slideDown("fast", cb);
			} else {
				$(this).slideUp("fast", cb);
			}
		});
	};
})(jQuery);
d.dyn = {};
d.dyn.version = "20110126";
d.dyn.status = {};
d.dyn.waiting = {};
d.dyn.success = function(url) {
	d.dyn.status[url] = "loaded";
	$.each(d.dyn.waiting[url], function() {
		this();
	});
	delete (d.dyn.waiting[url]);
};
d.dyn.load = function(url, cb) {
	if (d.dyn.status[url] === "loaded") {
		cb();
	} else {
		if (d.dyn.status[url] === "pending") {
			d.dyn.waiting[url].push(cb);
		} else {
			d.dyn.status[url] = "pending";
			d.dyn.waiting[url] = [ cb ];
			$
					.ajax({
						url : url + "?" + $.param({
							v : d.dyn.version
						}),
						dataType : "text",
						cache : true,
						success : function(code) {
							code += '\n d.dyn.success('
									+ d.utils.jsonQuote(url) + ');';
							$.globalEval(code);
						}
					});
		}
	}
};
d.dyn.loadAll = function(urls, cb) {
	var called = false;
	var check = function() {
		if (!called) {
			var notReady = $.map(urls, function(url) {
				return d.dyn.status[url] === "loaded" ? null : url;
			});
			if (notReady.length === 0) {
				cb();
				called = true;
			}
		}
	};
	$.each(urls, function(i, url) {
		d.dyn.load(url, check);
	});
};
d.dyn.needUiBloat = function(cb) {
	d.dyn.load("/js/jQueryUi/jquery-ui-1.8.6.custom.doodle.min.js", cb);
};
d.utils = {};
d.utils.handlers = {};
d.utils.eventLog = [];
d.utils.subscribeTo = function(event, handler) {
	d.utils.handlers[event] = d.utils.handlers[event] || [];
	d.utils.handlers[event].push(handler);
};
d.utils.trigger = function(event, data, trigger) {
	d.utils.eventLog.push([ new Date(), event ]);
	$.each(d.utils.handlers[event] || [], function() {
		this(data, trigger);
	});
};
d.utils.join2 = function(strArray, separator, lastSeparator) {
	var resultStr = "";
	$.each(strArray, function(i, str) {
		resultStr += str;
		if (i < strArray.length - 2) {
			resultStr += separator;
		} else if (i === strArray.length - 2) {
			resultStr += lastSeparator;
		}
	});
	return resultStr;
};
d.utils.jsonQuote = function(str) {
	if (!str || str.length === 0) {
		return "\"\"";
	}
	var b, c = 0;
	var len = str.length;
	var sb = "";
	var t;
	sb += '"';
	for ( var i = 0; i < len; i += 1) {
		b = c;
		c = str.charAt(i);
		switch (c) {
		case '\\':
		case '"':
			sb += '\\';
			sb += c;
			break;
		case '/':
			if (b === '<') {
				sb += '\\';
			}
			sb += c;
			break;
		case '\b':
			sb += "\\b";
			break;
		case '\t':
			sb += "\\t";
			break;
		case '\n':
			sb += "\\n";
			break;
		case '\f':
			sb += "\\f";
			break;
		case '\r':
			sb += "\\r";
			break;
		default:
			if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
					|| (c >= '\u2000' && c < '\u2100')) {
				t = "000" + c.charCodeAt(0).toString(16);
				sb += "\\u" + t.substring(t.length - 4);
			} else {
				sb += c;
			}
		}
	}
	sb += '"';
	return sb;
};
d.utils.log = function(message) {
	if (typeof (console) !== 'undefined' && console !== null) {
		console.log(message);
	}
};
d.utils.messageFormat = function(pattern) {
	var re = /'([^']+)'|('')|\{(\d+)\}|([^'{]+)/g;
	var str = "";
	var result = re.exec(pattern);
	while (result) {
		if (result[1]) {
			str += result[1];
		} else if (result[2]) {
			str += "'";
		} else if (result[3]) {
			str += arguments[parseInt(result[3], 10) + 1];
		} else if (result[4]) {
			str += result[4];
		}
		result = re.exec(pattern);
	}
	return str;
};
d.utils.askConfirmation = function(e) {
	d.dyn.needUiBloat(function() {
		var content = $('<p style="word-wrap: break-word;"/>');
		if (e.data.html === undefined) {
			content.text(e.data.text);
		} else {
			content.html(e.data.html);
		}
		$("#content").append(
				$('<div/>').attr("id", "dialog-confirm").append(
						$('<h1 class="orange spaceDAfter"/>')
								.text(e.data.title)).append(content));
		var buttons = [ {
			text : e.data.yes,
			'class' : "yes",
			click : function() {
				e.data.yesfn(e.data.yesParams);
				$(this).dialog("close");
				$(this).remove();
			}
		}, {
			text : e.data.no,
			'class' : "no",
			click : function() {
				$(this).dialog("close");
				$(this).remove();
			}
		} ];
		$("#dialog-confirm").dialog({
			resizable : false,
			width : 600,
			zIndex : 8000,
			modal : true,
			buttons : buttons
		});
	});
	return false;
};
d.utils.showInformation = function(e) {
	d.dyn.needUiBloat(function() {
		var content = $('<p style="word-wrap: break-word;"/>');
		if (e.data.html === undefined) {
			content.text(e.data.text);
		} else {
			content.html(e.data.html);
		}
		$("#content").append(
				$('<div/>').attr("id", "dialog-info").append(
						$('<h1 class="spaceDAfter"/>').addClass("orange").text(
								e.data.title)).append(content));
		var buttons = {};
		buttons[e.data.ok] = function() {
			if (e.data.okfn) {
				e.data.okfn(e.data.okParams);
			}
			$(this).dialog("close");
			$(this).remove();
		};
		$("#dialog-info").dialog({
			resizable : false,
			width : 600,
			modal : true,
			buttons : buttons,
			zIndex : 8000
		});
	});
	return false;
};
d.utils.initAjaxErrorHandler = function() {
	$('#content')
			.ajaxError(
					function(e, xhr, settings, exception) {
						var errorMessageHTML = "&rsaquo; "
								+ d.utils.l10n.errorOccurred + ": "
								+ xhr.statusText + " (" + xhr.status + ")";
						if ($("#ajaxError").length > 0) {
							$("#ajaxError").prepend(
									$('<p/>').html(errorMessageHTML));
						} else {
							var reloadLink = $('<a href="#"/>').html(
									"<br/>&raquo; "
											+ d.utils.l10n.clickToReload)
									.click(function() {
										location.reload();
										return false;
									});
							$('#content')
									.before(
											$(
													'<div id="ajaxError" class="maintenanceMessage"/>')
													.append(
															$('<p/>')
																	.html(
																			errorMessageHTML))
													.append(reloadLink));
						}
						d.utils.trigger("ajaxError");
					});
};
d.utils.rescueHooks = [];
d.utils.getRescueData = function() {
	var rescueMap = {};
	$(".rescueData").each(function() {
		if (!$(this).is(":checkbox") || $(this).attr("checked")) {
			if (!$(this).isHint()) {
				rescueMap[$(this).attr("id")] = $(this).val();
			}
		}
	});
	$.each(d.utils.rescueHooks, function() {
		$.extend(rescueMap, this());
	});
	rescueMap.hash = d.nav.hash;
	var rescueFields = [];
	$.each(rescueMap, function(key, val) {
		rescueFields
				.push(d.utils.jsonQuote(key) + ":" + d.utils.jsonQuote(val));
	});
	return "{" + rescueFields.join(",") + "}";
};
d.utils.prefillRescuedData = function() {
	if (d.utils.rescue.hash) {
		window.location.hash = d.utils.rescue.hash;
		d.nav.navigate();
	}
	$.each(d.utils.rescue, function(key, value) {
		var field = $('[id=' + key.replace(/([^\w])/g, "\\$1") + ']');
		if (field.hasClass("rescueData")) {
			if (field.is(":checkbox")) {
				field.attr("checked", value !== "");
			} else {
				field.removeClass("hintText").val(value);
			}
		}
	});
};
d.utils.timeZone = null;
d.utils.setTimeZone = function(timeZone) {
	if (timeZone !== d.utils.timeZone) {
		d.utils.timeZone = timeZone;
		d.utils.trigger("timeZoneChange");
	}
};
d.myDoodle = {};
d.myDoodle.forceLoginNeeded = function(callback, doNotAddEvent) {
	if (callback && !doNotAddEvent) {
		d.utils.subscribeTo("logout", d.myDoodle.forceLoginNeeded);
		d.utils.subscribeTo("login", function() {
			d.myDoodle.forceLoginNeeded(callback, true);
		});
	}
	if (d.myDoodle.user.loggedIn && d.myDoodle.neededUser
			&& d.myDoodle.neededUser.id
			&& d.myDoodle.user.id !== d.myDoodle.neededUser.id) {
		$("#loggedOutContent").remove();
		$("#content").children().not("script").hide();
		var wrongUser = $($('<div id="loggedOutContent"/>'));
		wrongUser.append($('<h3 class="spaceCAfter">').text(d.l10n.myDoodle));
		wrongUser
				.append($('<p class="h4"/>')
						.html(
								d.utils
										.messageFormat(
												d.myDoodle.l10n.loggedInWrongUser,
												'<b>' + d.myDoodle.user.name
														+ '</b>',
												'<b>'
														+ d.myDoodle.neededUser.name
														+ '</b>',
												'<a href="#" onclick="d.myDoodle.logout();return false;">',
												'</a>')));
		$("#content").append(wrongUser);
	} else if (d.myDoodle.user.loggedIn) {
		$("#loggedOutContent").remove();
		$("#content").children().not("script").show();
		if (callback) {
			callback();
		}
		if (d.nav.hash) {
			d.utils.trigger("navigateConstruct", d.nav.hash);
		}
	} else {
		d.dyn.load("/js/mydoodle/mydoodle.js", function() {
			var loginForm = d.myDoodle.needUserLogin();
			$("#loggedOutContent").remove();
			$("#content").children().not("script").hide();
			$("#content").append(loginForm);
			$("#loggedOutContent").show();
		});
	}
};
d.myDoodle.setBaseUrl = function(url) {
	d.myDoodle.baseUrl = url;
};
d.myDoodle.setFacebookAuthUrl = function(url) {
	d.myDoodle.facebookAuthUrl = url;
};
d.myDoodle.status = function() {
	var l10n = d.utils.l10n;
	var html;
	if (d.myDoodle.user.loggedIn) {
		html = $('<div id="loginLinks"/>');
		html.append($('<a class="mydoodle" href="mydoodle/polls.html"/>').text(
				d.myDoodle.user.unverifiedEmailAddress));
		var actions = $('<span class="actions"/>');
		actions.append('<span> · </span>');
		actions.append($('<a href="mydoodle/polls.html"/>').text(
				l10n.static_myDoodle));
		actions.append('<span> · </span>');
		actions.append($('<a href="mydoodle/account.html"/>').text(
				l10n.manageAccount));
		actions.append('<span> · </span>');
		actions.append($('<a href="#"/>').text(l10n.logOut).click(function() {
			d.myDoodle.logout($("#login"));
			return false;
		}));
		html.append(actions);
	} else {
		html = $('<div id="loginLinks"/>');
		var link = $('<a href="#" id="activateLogin"/>').text(
				l10n.logIn + " (" + l10n.optional + ")");
		link.click(function() {
			d.dyn.load("/js/mydoodle/mydoodle.js", function() {
				d.myDoodle.activateLogin($("#login"));
			});
			return false;
		});
		html.append(link);
	}
	$("#login").subst(html);
	if (d.myDoodle.switchToOldUrl) {
		d.myDoodle.addSwitchToOldDesignLinks();
	}
};
d.myDoodle.addSwitchToOldDesignLinks = function() {
	$("#loginLinks").prepend('<span> · </span>');
	$("#loginLinks").prepend(
			$('<a/>').attr("href", d.myDoodle.switchToOldUrl).text(
					d.utils.l10n.oldDesign));
};
d.myDoodle.logout = function(node) {
	$.post("/mydoodle/ajaxLogout", {}, function(data) {
		if (data.success) {
			d.myDoodle.user = data.user;
			d.myDoodle.token = data.token;
			d.myDoodle.status(node);
			d.utils.trigger("logout");
		}
	}, "json");
};
d.footer = {};
d.footer.buildFooter = function() {
	var f = $('<div/>');
	var langText = "";
	$.each(d.footer.lang.languages, function() {
		if (d.myDoodle.viewLocale === this[0]) {
			langText = this[1];
		}
	});
	if (langText === "") {
		$.each(d.footer.lang.languages, function() {
			if (d.myDoodle.viewLocale.substring(0, 2) === this[0]) {
				langText = this[1];
			}
		});
	}
	if (langText === "") {
		langText = "en";
	}
	var foot = $('<div class="footerlinks"/>');
	foot.append($('<a id="languageExpander" class="expander"/>').text(langText)
			.click(d.footer.lang.toggleSelector));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append($('<a href="/"/>').text(d.utils.l10n.home)));
	foot.append($('<span/>').text("|"));
	if (d.myDoodle.viewLocale === "de") {
		foot.append($('<div/>').append($('<a href="/blog/"/>').text("Blog")));
	} else {
		foot.append($('<div/>').append(
				$('<a href="/blog/english"/>').text("Blog")));
	}
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="about/about.html"/>').text(d.utils.l10n.about)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/advertising.html"/>').text(
					d.utils.l10n.advertising)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/media.html"/>').text(d.utils.l10n.media)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/tos.html"/>').text(d.utils.l10n.terms)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/policy.html"/>').text(d.utils.l10n.privacy)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/help.html"/>').text(d.utils.l10n.help)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').append(
			$('<a href="/about/contact.html"/>').text(d.utils.l10n.contact)));
	foot.append($('<span/>').text("|"));
	foot.append($('<div/>').text("© Doodle AG").css("white-space", "nowrap"));
	f.append(foot);
	f.append($('<div id="languageSelector" style="display: none;"/>'));
	return f;
};
d.footer.lang = {};
d.footer.lang.toggleSelector = function() {
	if ($("#languageSelector").is(":empty")) {
		d.footer.lang.createSelector();
	}
	$("#languageExpander").toggleClass("expanderUp");
	$("#languageSelector").animateToggle();
};
d.footer.lang.languages = [ [ "en", "English" ], [ "en_GB", "English (UK)" ],
		[ "de", "Deutsch" ], [ "fr", "Français" ], [ "it", "Italiano" ],
		[ "rm", "Rumantsch" ], [ "ar", "العربية" ], [ "bg", "български" ],
		[ "br", "Brezhoneg" ], [ "ca", "Català" ], [ "cs", "Čeština" ],
		[ "da", "Dansk" ], [ "el", "ελληνικά" ], [ "eo", "Esperanto" ],
		[ "es", "Español" ], [ "eu", "Euskara" ], [ "fi", "Suomi" ],
		[ "hu", "Magyar" ], [ "in", "Bahasa Indonesia" ], [ "iw", "עִבְרִית" ],
		[ "lt", "Lietuvių" ], [ "nl", "Nederlands" ], [ "pl", "Polski" ],
		[ "pt", "Português" ], [ "ru", "Русский" ], [ "sl", "Slovenščina" ],
		[ "sv", "Svenska" ], [ "tr", "Türkçe" ], [ "uk", "Українська" ],
		[ "zh", "中文简体" ], [ "zh_TW", "中文繁體" ] ];
d.footer.lang.createSelector = function() {
	var langs = $('<form id="languages" method="post" action=""/>');
	$.each(d.footer.lang.languages, function() {
		if (d.myDoodle.viewLocale === this[0]) {
			langs.append($('<span/>').text(this[1]));
		} else {
			langs.append($('<a/>').text(this[1]).bind('click', {
				locale : this[0]
			}, d.footer.lang.changeLanguage)).append(" ");
		}
	});
	$("#languageSelector").append(langs);
};
d.footer.lang.changeLanguage = function(e) {
	$("#languages").append(
			$('<input type="hidden" name="locale"/>').val(e.data.locale));
	$("#languages").append(
			$('<input type="hidden" name="rescuedData"/>').val(
					d.utils.getRescueData()));
	$("#languages").submit();
};
d.utils.theming = {};
d.utils.theming.removeTheme = function() {
	if (!d.utils.theming.data.keepTheme) {
		$("style[title='premium']").remove();
	}
};
d.utils.theming.loadTheme = function() {
	if (!d.utils.theming.data.keepTheme && d.myDoodle.user.hasCustomTheme) {
		if (d.meetme) {
			$("#skyrightcontainer > #skyright > div").css('width', 'auto');
			$("#skyright > div").remove();
			$("#banner > div").remove();
		} else {
			$.get('np/theming/' + encodeURIComponent(d.myDoodle.user.id), {},
					function(data) {
						if (data !== "") {
							$("#skyright > div").remove();
							$("#banner > div").remove();
							$("head").append(data);
							$("#banner").append('<div class="themedBanner"/>');
							$("#skyright").append(
									'<div class="themedSkyscraper"/>');
							$("#skyrightcontainer > #skyright > div").css(
									'width', 'auto');
						}
					}, "html");
		}
	}
};
d.utils.theming.init = function() {
	d.utils.subscribeTo("logout", d.utils.theming.removeTheme);
	d.utils.subscribeTo("login", d.utils.theming.loadTheme);
};
d.nav = {};
d.nav.hash = undefined;
d.nav.allowed = function() {
	if (d.poll
			&& !d.poll.grantWrite
			&& (d.nav.hash === "#admin" || d.nav.hash === "#history" || d.nav.hash === "#notifications")) {
		return false;
	} else if (d.meetme && !d.meetme.grantWrite() && d.nav.hash === "#admin") {
		return false;
	}
	return true;
};
d.nav.navigate = function(callback) {
	if (!d.nav.allowed()) {
		window.location.hash = "";
	}
	if (d.nav.hash !== window.location.hash) {
		var oldHash = d.nav.hash;
		d.nav.hash = window.location.hash;
		if ((d.nav.hash === "#" || $("" + d.nav.hash).size() === 0)
				&& oldHash !== undefined) {
			d.utils.trigger("navigateDestruct", oldHash, callback);
		}
		d.utils.trigger("navigateConstruct", d.nav.hash, callback);
	}
};
d.nav.navigateTo = function(hash) {
	window.location.hash = hash;
	d.nav.navigate(true);
	return false;
};
d.utils.encode = function(text) {
	return $('<div/>').text(text).html();
};
d.utils.decode = function(html) {
	return $('<div/>').html(html).text();
};
d.utils.store = {};
d.utils.store.readList = function(varName) {
	if (sessionStorage[varName]) {
		return sessionStorage[varName].split("|");
	} else {
		return [];
	}
};
d.utils.store.append = function(varName, value) {
	if (sessionStorage[varName] !== undefined) {
		sessionStorage[varName] = sessionStorage[varName] + "|" + value;
	} else {
		sessionStorage[varName] = value;
	}
};
d.utils.store.contains = function(varName, value) {
	var contains = false;
	$.each(d.utils.store.readList(varName), function(i, val) {
		if (val === value + '') {
			contains = true;
		}
	});
	return contains;
};
d.ui = {};
d.ui._btnDown = function() {
	$(this).addClass("pressed");
};
d.ui._btnUp = function() {
	$(this).removeClass("pressed");
};
d.ui.generateBigButton = function(value) {
	var bigButton = $('<a href="#"/>').addClass('bigButton');
	bigButton = bigButton.append($('<div class="left"/>')).append(
			$('<div class="center"/>').text(value)).append(
			$('<div class="right"/>'));
	bigButton.mousedown(d.ui._btnDown).bind("mouseup mouseout", d.ui._btnUp);
	return bigButton;
};